// ignore_for_file: always_specify_types

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:medical_pro_flutter/api/Api.dart';
import 'package:medical_pro_flutter/components/dialog/LoadingDialog.dart';
import 'package:medical_pro_flutter/components/dialog/SuccessDialog.dart';
import 'package:medical_pro_flutter/components/illcase/ShowCasePage.dart';
import 'package:medical_pro_flutter/entity/IllCase.dart';

class SearchCaseList extends StatefulWidget {
  SearchCaseList({Key? key}) : super(key: key);

  @override
  _SearchCaseListState createState() => _SearchCaseListState();
}

class _SearchCaseListState extends State<SearchCaseList> {
  TextEditingController searchText = TextEditingController();
  final controller = TextEditingController();
  List caseInfo = [];

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(
      children: [
        Container(
          color: Theme.of(context).primaryColor,
          margin: EdgeInsets.only(top: 1.0),
          child: Padding(
            padding: EdgeInsets.only(top: 10.0, bottom: 1.0),
            child: Container(
              // decoration: BoxDecoration(
              //   border: Border.all(
              //     color: Colors.red,
              //     width: 3,
              //   ),
              // ),
              height: 80.0,
              child: Padding(
                  padding: const EdgeInsets.all(6.0),
                  child: Card(
                      child: Container(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        // SizedBox(
                        //   width: 5.0,
                        // ),
                        // Icon(
                        //   Icons.search,
                        //   color: Colors.grey,
                        // ),
                        Expanded(
                          child: Container(
                            height: 100,
                            // decoration: BoxDecoration(
                            //   border: Border.all(
                            //     color: Colors.red,
                            //     width: 1,
                            //   ),
                            // ),
                            alignment: Alignment.center,
                            child: TextField(
                              controller: searchText,
                              decoration: InputDecoration(
                                contentPadding: EdgeInsets.only(top: 0.0),
                                hintText: '输入身份证号',
                                border: OutlineInputBorder(
                                  ///设置边框四个角的弧度
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)),

                                  ///用来配置边框的样式
                                  borderSide: BorderSide(
                                    ///设置边框的颜色
                                    color: Colors.black,

                                    ///设置边框的粗细
                                    width: 2.0,
                                  ),
                                ),
                              ),
                              // onChanged: onSearchTextChanged,
                            ),
                          ),
                        ),
                        IconButton(
                            icon: Icon(Icons.search),
                            color: Colors.grey,
                            iconSize: 18.0,
                            onPressed: _submitSearch),
                      ],
                    ),
                  ))),
            ),
          ),
        ),
        Container(
          // height: 1500.0,
          padding: EdgeInsets.all(10),
          margin: EdgeInsets.fromLTRB(10, 5, 5, 10),
          child: _getCaseList(),
        ),

        // _getCaseList(),
      ],
    ));
  }

  _submitSearch() async {
    if (searchText.text.isEmpty) {
      Fluttertoast.showToast(
        msg: '您未输入任何内容',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      return;
    }
    controller.clear();

    String url = API.BASE_URL + API.ILL_Case + 'IDnum/' + searchText.text;

    print('发出请求：$url');
    Response response;

    try {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return LoadingDialog(text: '加载中...');
          });
      var dio = Dio();
      response = await dio.get(url);
      dio.close();

      if (response.statusCode == 200) {
        print(response.data);
        // List<IllCase> va = json.decode(response.data);
        List va = List<dynamic>.from(response.data);
        setState(() {
          caseInfo = va;
        });
        if (caseInfo.isEmpty) {
          Navigator.pop(context);
          Fluttertoast.showToast(
            msg: '找不到与输入相符的病例',
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            timeInSecForIosWeb: 3,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0,
          );
          return;
        }
        print(caseInfo[0]['case_id']);
        print('总共${caseInfo.length}个病例');

        Navigator.pop(context);
      }
    } catch (e) {
      print(e);
    }
  }

  Widget _getCaseList() {
    if (caseInfo.length != 0) {
      return ListView.builder(
          // scrollDirection: Axis.vertical,
          shrinkWrap: true,
          physics:
              NeverScrollableScrollPhysics(), //禁用滑动事件,不加这个ListView 套在Column里不能滑动
          itemCount: caseInfo.length,
          itemBuilder: (BuildContext context, int index) {
            return _itemBuilder(context, index);
          });
    } else {
      // 加载菊花
      return Text('暂无数据');
    }
  }

  Widget _itemBuilder(BuildContext context, int index) {
    return ListTile(
        title: Text('患者姓名：${caseInfo[index]['patient_name']}'),
        subtitle: Text('诊断日期：${caseInfo[index]['date']}'),
        onTap: () {
          print('点击了$index条');
          Navigator.pushNamed(context, '/show_case_page',
              arguments: caseInfo[index]);
        }
        // () => ShowCasePage(caseInfo[index])
        );
  }
}
